package com.gzhryc.shared_device.oem.h5.mng.jetty;

import java.io.IOException;
import java.util.Date;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.gzhryc.common.PatternHelper;
import com.gzhryc.common.StringTools;
import com.gzhryc.common.data.dto.AjaxResult;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.common.redis.RedisTools;
import com.gzhryc.shared_device.oem.code.RedisDBConstants;
import com.gzhryc.shared_device.oem.h5.mng.WebConstants;
import com.gzhryc.servlet.DtoConstants;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.system.ManagerService;
import com.gzhryc.system.SysConstants;
import com.gzhryc.system.dao.db.Manager;
import org.apache.commons.lang3.time.DateFormatUtils;

public class AjaxSecurityFilter implements Filter {

	static Logger log = Logger.getLogger(AjaxSecurityFilter.class);

	PatternHelper patternHelper;

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		patternHelper = new PatternHelper();
		patternHelper.addExcludePattern(Pattern.compile("/mng/login\\.do"));
		//用于URL访问锁
		patternHelper.addMatchedPatternList(Pattern.compile("^.*\\.do$"));
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpRequest = HttpServletRequest.class.cast(request);
		HttpServletResponse httpResponse = HttpServletResponse.class.cast(response);

		String uri = httpRequest.getRequestURI();
		if (patternHelper.isExclude(uri)) {
			chain.doFilter(httpRequest, httpResponse);
			return;
		}
		
		Manager manager = null;
		HttpSession session = httpRequest.getSession(false);
		if (session != null) {
			manager = WebUtils.getAttribute(session, SysConstants.SESSION_LOGIN_MANAGER, Manager.class);
		}
			
		if(manager == null) {
			//检查COOKIES
			String token = WebUtils.getCookies(httpRequest, SysConstants.COOKIES_LOGIN_TOKEN);
			if(StringTools.isNotBlank(token)) {
				manager = ManagerService.self().getByToken(token);
				if(manager != null) {
					session = httpRequest.getSession(true);
					session.setAttribute(SysConstants.SESSION_LOGIN_MANAGER, manager);
				}
			}
		}
			
		if (manager != null) {
			if(WebConstants.isDebug() > 1){
				log.info("测试模式访问：" + uri);
				httpRequest.setAttribute(SysConstants.LOGIN_MANAGER, manager);
				// 记录日志
				WebConstants.setSysLog(httpRequest, manager);
				chain.doFilter(httpRequest, httpResponse);
				return;
			}

			if(patternHelper.isMatched(uri,false)) {
				//URL访问锁
				String key = uri + "_" + manager.getId();
				String date = DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss");
				if (RedisTools.get().setnx(RedisDBConstants.URL_LOCK_DB, key, date, 2L)) {
					httpRequest.setAttribute(SysConstants.LOGIN_MANAGER, manager);
					// 记录日志
					WebConstants.setSysLog(httpRequest, manager);
					chain.doFilter(httpRequest, httpResponse);
				} else {
					AjaxResult result = new AjaxResult(DtoConstants.FREQUENT_VISITS, "访问过于频繁");
					WebUtils.toJson(httpResponse, result);
				}
			}else{
				httpRequest.setAttribute(SysConstants.LOGIN_MANAGER, manager);
				// 记录日志
				WebConstants.setSysLog(httpRequest, manager);
				chain.doFilter(httpRequest, httpResponse);
			}
			return;
		}

		AjaxResult result = new AjaxResult(DtoConstants.LOGIN_OVERDUE, "登录过期，请重新登录");
		WebUtils.toJson(httpResponse, result);
	}

	@Override
	public void destroy() {
	}
}
